package ccm.itesm.mx.servicios;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Roster extends ListActivity {

	ArrayList<String> alumnos = new ArrayList<String>();
	ArrayList<JSONObject> jsonarr = new ArrayList<JSONObject>();
	private String opciones[];
	String crn = null;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.faltas);
		Bundle bundle = this.getIntent().getExtras();
		crn = bundle.getString("crn");
		cargaAlumno();

		this.setListAdapter(new ArrayAdapter<String>(this,
				R.layout.listactivity, alumnos));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		switch (position) {
		default:
			String nombre = "";
			String matricula = "";
			String categoria = "";
			String rama = "";
			String carrera = "";
			String posicion = "";

			try {
				nombre = ""
						+ jsonarr.get(position).getString("nombre");
				matricula = "Matricula: "
						+ jsonarr.get(position).getString("matricula");
				carrera = "Carrera: "
						+ jsonarr.get(position).getString("carrera");
				categoria = "Categoria: "
						+ jsonarr.get(position).getString("categoria");
				rama = "Rama: " + jsonarr.get(position).getString("rama");
				posicion = "Posicion: "
						+ jsonarr.get(position).getString("posicion");

				Bundle bunny = new Bundle();
				bunny.putString("nombre", nombre);
				bunny.putString("matricula", matricula);
				bunny.putString("categoria", categoria);
				bunny.putString("rama", rama);
				bunny.putString("carrera", carrera);
				bunny.putString("posicion", posicion);

				this.startActivity(new Intent(this, Alumno.class)
						.putExtras(bunny));

			} catch (JSONException e) {
				e.printStackTrace();

			}

			break;

		}
	}

	private void cargaAlumno() {

		String consulta = "http://modulocampusandroid.appspot.com/JsonAlumno?crn="
				+ crn;
		String respuesta = download(consulta);

		if (respuesta != null && !respuesta.startsWith("Error")) {
			try {
				JSONArray resu = new JSONArray(respuesta);
				for (int i = 0; i < resu.length(); i++) {
					JSONObject equipolist = resu.getJSONObject(i);
					jsonarr.add(equipolist);
					this.alumnos.add(equipolist.getString("nombre"));

				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block

				Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG)
						.show();
			}
		}

	}

	private String download(String urlString) {

		InputStream in = null;
		byte[] data = null;
		URLConnection conn = null;
		try {
			URL url = new URL(urlString);
			conn = url.openConnection();

			if ((conn instanceof HttpURLConnection)) {
				HttpURLConnection httpConn = (HttpURLConnection) conn;
				httpConn.setAllowUserInteraction(false);
				httpConn.setInstanceFollowRedirects(true);
				httpConn.setRequestMethod("GET");
				httpConn.connect();

				if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					in = httpConn.getInputStream();
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					int c;
					while ((c = in.read()) > -1)
						baos.write(c);
					data = baos.toByteArray();
					baos.close();
					in.close();
					String str = new String(data);
					return str;
				} else {
					return ("Error reading data");
				}
			}
		} catch (Exception ex) {
			return ("Error in connection");
		} finally {
			try {
				if (conn != null) {
					conn = null;
				}
				if (in != null) {
					in.close();
					in = null;
				}

			} catch (IOException ex) {
				return ("Error: " + ex.getMessage());
			}
		}
		return null;
	}

}